// 
//  Copyright 2011  Joel Johnson
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace TemplateCompiler {
	public class XmlDocument {
		public List<XmlObject> Elements {get; private set;}
		public XmlObject FirstTag {
			get {
				foreach(XmlObject xmlObject in Elements) {
					if(!(xmlObject is XmlContent)) {
						return xmlObject;
					}
				}
				return null;
			}
		}

		public XmlDocument() {
			Elements = new List<XmlObject>();
		}
		
		public void AddTag(XmlObject element) {
			element.PrettyPrint = false;
			Elements.Add(element);
		}
		
		public override string ToString () {
			StringBuilder sb = new StringBuilder();
			Elements.ForEach(e => sb.Append(e.ToString()));
			return sb.ToString();
		}
		
		public static XmlDocument Parse(String xml) {
			byte[] byteArray = Encoding.ASCII.GetBytes(xml);
			MemoryStream stream = new MemoryStream(byteArray);
			return Parse(new StreamReader(stream));
		}
		
		public static XmlDocument Parse(StreamReader reader) {	
			XmlDocument document = new XmlDocument();
			
			Stack<XmlObject> previousObject = new Stack<XmlObject>();
			XmlObject currentObject = null;
			StringBuilder sb = new StringBuilder();
			
			int nextI = reader.Read();
			while(nextI >= 0) {
				char next = (char)nextI;
				char peek = (char)reader.Peek();
				if(next == '<') {
					if(sb.Length > 0) {
						#region >Content<
						XmlContent content = new XmlContent(sb.ToString());
						if(currentObject == null) {
							document.AddTag(content);
						} else {
							currentObject.AddTag(content);
						}
						sb = new StringBuilder();
						#endregion
					}
					if(peek == '%') {
						#region <% special tag %>
						sb.Append(next);
						sb.Append((char)reader.Read());
						while(true) {
							nextI = reader.Read();
							if(nextI == -1) {
								throw new XmlParseException();
							}
							next = (char)nextI;
							peek = (char)reader.Peek();
							sb.Append(next);
							if(next == '%' && peek == '>') {
								sb.Append((char)reader.Read());
								XmlSpecial specialTag = XmlSpecial.Parse(sb.ToString());
								if(currentObject == null) {
									document.AddTag(specialTag);
								} else {
									currentObject.AddTag(specialTag);
								}
								sb = new StringBuilder();
								break;
							}
						}
						#endregion
					} else if(peek == '/') { 
						#region </Close Tag>
						while(true) {
							sb.Append(next);
							nextI = reader.Read();
							if(nextI == -1) {
								throw new XmlParseException();
							}
							next = (char)nextI;
							if(next == '>') {
								sb.Append(next);
								if(previousObject.Count > 0) {
									currentObject = previousObject.Pop();
								}
								sb = new StringBuilder();
								break;
							}
						}
						#endregion
					} else {
						#region <Normal Tag>
						while(true) {
							sb.Append(next);
							nextI = reader.Read();
							if(nextI == -1) {
								throw new XmlParseException();
							}
							next = (char)nextI;
							peek = (char)reader.Peek();
							if(next == '/' && peek == '>') {
								sb.Append(next);
								sb.Append((char)reader.Read());
								XmlObject normalTag = XmlObject.Parse(sb.ToString());
								if(currentObject == null) {
									document.AddTag(normalTag);
									currentObject = normalTag;
								} else {
									currentObject.AddTag(normalTag);
								}
								sb = new StringBuilder();
								break;
							} else if(next == '>') {
								sb.Append(next);
								XmlObject normalTag = XmlObject.Parse(sb.ToString());
								sb = new StringBuilder();
								if(currentObject == null) {
									document.AddTag(normalTag);
								} else {
									currentObject.AddTag(normalTag);
									previousObject.Push(currentObject);
								}
								currentObject = normalTag;
								break;
							}
						}
						#endregion
					}
				} else {
					sb.Append(next);
				}
				
				nextI = reader.Read();
			}
			if(sb.Length > 0) {
				XmlContent content = new XmlContent(sb.ToString());
				document.AddTag(content);
			}
			
			return document;
		}
		
		public static void Main() {
			string html =	"<%@ MILK %>\n" +
							"<%@ tag name='c' classname='DailyLog.Tags' %>\n" +
							"<html>\n" +
							"    <body>\n" +
							"        <div>some content</div>\n" +
							"        <div>\n" +
							"            <c:if value='true'>Do something</c:if>\n" +
							"            <span with=\"anattribute\" />\n" +
							"        </div>\n" +
							"        <span with=\"t'w'o\" different='att\"rib\"utes' />\n" +
							"        <span with=\"anattribute\" />\n" +
							"        <span with='a space' />\n" +
							"        <span with=\"a space\" />\n" +
							"    </body>\n" +
							"    <%= \"hello\" %>\n" +
							"    <% \"hello\".ToString(); %>\n" +
						  	"</html>\n";
			XmlDocument document = XmlDocument.Parse(html);
			Console.WriteLine (document);
			CSharpCompiler compiler = new CSharpCompiler("test.milk");
			compiler.Parse(document);
		}
	}
	
	public class XmlParseException : Exception {
		public XmlParseException() : base("Error while parsing XML") {}
	}
}